package com.pingbu.tijian.hospital.backapi.service;



import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pingbu.common.bean.ResultBean;
import com.pingbu.tijian.hospital.backapi.bean.entity.Student;
import com.pingbu.tijian.hospital.backapi.bean.entity.UserPermission;
import com.pingbu.tijian.hospital.backapi.mapper.StudentMapper;
import com.pingbu.tijian.hospital.backapi.mapper.UserInfoMapper;
import com.pingbu.common.utils.PbSecretUtils;
import com.pingbu.tijian.hospital.backapi.bean.entity.UserInfo;
import com.pingbu.tijian.hospital.backapi.mapper.UserPermissionMapper;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class UserInfoService {

    private static Logger logger = LoggerFactory.getLogger(UserInfoService.class);

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserPermissionMapper userPermissionMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 根据登录账号和密码，获得用户信息
     * @param param
     * @return
     */
    public ResultBean<UserInfo> getUserByCodeAndPwd(UserInfo param) {

        if(param==null){
            return ResultBean.create(10,"由于未知原因登录验证失败，请联系管理员");
        }
        // 1 判断code是否为空
        if(StringUtils.isEmpty(param.getUsercode())){
            return ResultBean.create(20,"请填写登录账号");
        }
        // 2 判断pwd 是否为空
        if(StringUtils.isEmpty(param.getUserpwd())){
            return ResultBean.create(30,"请填写登录密码");
        }

        // 3 根据code 获取UserInfo对象
        UserInfo ui1 = new UserInfo();
        ui1.setUsercode(param.getUsercode());
        UserInfo ui1res = userInfoMapper.get(ui1);




        if(ui1res==null){
            return ResultBean.create(40,"登录账号错误，未能获得正确的用户信息");
        }

        // 4 验证密码是否正确
        String pwdmd5=PbSecretUtils.md5( param.getUserpwd() );

        // 如果密码未加密，则更新密码未加密
        if(ui1res.getUserpwd().equals( param.getUserpwd() )){
            ui1res.setUserpwd(pwdmd5);
            userInfoMapper.update(ui1res);
        }

        // 登录密码错误。
        if(!pwdmd5.equals(ui1res.getUserpwd())){
            return ResultBean.create(50,"登录密码错误");
        }

        String noid = ui1res.getNoid();
        List<String> userPermission =  userInfoMapper.getUserPermissionByUserId(noid);
        ui1res.setPermissions(userPermission);
        // 5 返回的用户信息，不能带着密码内容
        ui1res.setUserpwd(null);

        return ResultBean.create(0, "登录成功",ui1res);
    }

    /**
     * 对用户列表进行分页
     * @param param
     * @return
     */
    public ResultBean<PageInfo<UserInfo>> doPage(UserInfo param){


        PageHelper.startPage(param.getPageNum(),param.getPageSize());

        List<UserInfo> lst1 = userInfoMapper.list(param);

        for(UserInfo ui1 : lst1){
            ui1.setUserpwd("");
            // 更新每个人员的权限
            String userId = ui1.getNoid();

            // 读取每个人员的权限
            UserPermission up = new UserPermission();
            up.setUser_id(ui1.getNoid());
            List<UserPermission> list2 = userPermissionMapper.list(up);
            // 整理成String集合类型的权限列表
            List<String> permissions = new ArrayList<>();
            for(UserPermission up1 : list2){
                permissions.add(up1.getPermission_value());
            }


            // 省略整理代码
            ui1.setPermissions(permissions);

        }

        PageInfo pi1 = new PageInfo(lst1);

        return ResultBean.create(0,"success",pi1);

    }

    /**
     * 增加用户
     */
    public ResultBean<Integer> add(UserInfo param){

        ////得到数据库对应param.getUsercode()的数据没有则新增
        UserInfo ui2=new UserInfo();
        ui2.setUsercode(param.getUsercode());
        UserInfo ui2Res = userInfoMapper.get(ui2);

        // 不存在，则新增
        if(ui2Res==null){
            param.setNoid(PbSecretUtils.uuid());
            param.setUserpwd( PbSecretUtils.md5(param.getUserpwd()) );
            userInfoMapper.insert(param);
            // 保存用户的权限记录，写到 t_user_permission 表里面，直接操作Mapper层

            List<String> perms = param.getPermissions();
            for(String p1:perms) {
                UserPermission up = new UserPermission();
                up.setNoid(PbSecretUtils.uuid());
                up.setUser_id(param.getNoid());
                up.setPermission_value(p1);
                userPermissionMapper.insert(up);
            }

        }else{
            return ResultBean.create(23,"该登录账号已经存在，无法新增。");
        }

        return ResultBean.create(0,"success");

    }

    /**
     * 删除用户
     * @param param
     * @return
     */
    public ResultBean<Integer> delete(UserInfo param){

        //
        UserInfo ui2=new UserInfo();
        ui2.setNoid(param.getNoid());
        Integer res2 = userInfoMapper.delete(ui2);

        // 先处理删除掉所有他的权限 UserPermission

        UserPermission up1 = new UserPermission();
        up1.setUser_id(param.getNoid());
        userPermissionMapper.delete(up1);
        return ResultBean.create(0, "success", res2);
//        try {
//            if (res2 > 0) {
//                return ResultBean.create(0, "success");
//            } else {
//                return ResultBean.create(0, "未找到需要删除的记录");
//            }
//        }catch(Exception err){
//            return ResultBean.create(43,"出现异常，删除失败："+err.getMessage());
//        }

    }

    /**
     * 修改用户
     * @param param
     * @return
     */
    public ResultBean<Integer> update(UserInfo param){
        UserInfo ui2=new UserInfo();
        ui2.setUsercode(param.getUsercode());
        ui2.setRealname(param.getRealname());
        ui2.setUserpwd(param.getUserpwd());
        Integer res2 = userInfoMapper.update(ui2);

        // 把 t_user_permission中用户所有的权限记录都删了，再新增

//        ui2.setPermissions(null);
        UserPermission up1 = new UserPermission();
        up1.setUser_id(param.getNoid());
        userPermissionMapper.delete(up1);

        List<String> perms = param.getPermissions();
        for(String p1:perms) {
            UserPermission up = new UserPermission();
            up.setNoid(PbSecretUtils.uuid());
            up.setUser_id(param.getNoid());
            up.setPermission_value(p1);
            userPermissionMapper.insert(up);
        }
//        ui2.setPermissions(param.getPermissions());
        return ResultBean.create(0, "success", res2);
    }

    /**
     * 查询当前用户的userecode是否存在，如果不存在，就新建，如果存在，直接返回
     * @param param
     * @return
     */
    public ResultBean<Integer> validUserCode(UserInfo param){
        UserInfo userInfo = userInfoMapper.get(param);
        if(userInfo == null){
            return  ResultBean.create(10,"err");
        }
        return ResultBean.create(0, "success");
    }
}
